<script lang="ts" setup name="UrbanShielding">
import { ref, reactive, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import type { FormInstance } from "element-plus";
import {
  getCityBlackList,
  getCityBlackCityList,
  getCityBlackAdd,
  getCityBlackDel,
} from "@/app/api/urbanShielding";

interface City {
  id: number;
  province: number;
  cityname: string;
  created_at: string;
}

interface Province {
  id: number;
  pid: number;
  cityname: string;
}

interface CityOption {
  id: number;
  pid: number;
  cityname: string;
}

// 表格数据
const tableData = ref<City[]>([]);
const loading = ref(false);
const total = ref(0);
const multipleSelection = ref<City[]>([]);

// 分页参数
const queryParams = reactive({
  page: 1,
  limit: 10,
  keyword: "",
});

// 对话框控制
const dialogVisible = ref(false);
const dialogTitle = ref("添加");

// 表单
const formRef = ref<FormInstance>();
const form = reactive({
  provinceId: null,
  cityId: null,
});

// 下拉选项
const provinceOptions = ref<Province[]>([]);
const cityOptions = ref<CityOption[]>([]);

// 表单校验规则
const rules = reactive({
  provinceId: [{ required: true, message: "请选择省份", trigger: "change" }],
});

// 获取表格数据
const getList = async () => {
  loading.value = true;
  try {
    const res = await getCityBlackList({
      ...queryParams,
    });
    tableData.value = res.data.data;
    total.value = res.data.total;
    loading.value = false;
  } catch (error) {
    console.error(error);
    loading.value = false;
  }
};

// 获取省份数据
const getProvinceList = async () => {
  try {
    const res = await getCityBlackCityList();
    provinceOptions.value = res.data;
  } catch (error) {
    console.error(error);
  }
};

// 根据省份获取城市数据
const getCityListByProvince = async (provinceId: number) => {
  try {
    const res = await getCityBlackCityList({
      pid: provinceId,
    });
    cityOptions.value = res.data;
  } catch (error) {
    console.error(error);
  }
};

// 处理省份变化
const handleProvinceChange = (value: number) => {
  console.log(value);
  form.cityId = null;
  if (value) {
    getCityListByProvince(value);
  } else {
    cityOptions.value = [];
  }
};

// 处理搜索
const handleSearch = () => {
  queryParams.page = 1;
  getList();
};

// 处理重置
const handleReset = () => {
  queryParams.keyword = "";
  handleSearch();
};

// 打开添加对话框
const handleAdd = () => {
  dialogTitle.value = "添加";
  dialogVisible.value = true;
  // 重置表单
  form.provinceId = null;
  form.cityId = null;
  cityOptions.value = [];

  // 获取省份数据
  getProvinceList();
};

// 处理删除选中
const handleDeleteSelected = () => {
  if (multipleSelection.value.length === 0) {
    ElMessage.warning("请至少选择一条记录");
    return;
  }

  const ids = multipleSelection.value.map((item) => item.id).join(",");
  handleDelete(ids);
};

// 处理删除单条
const handleDeleteItem = (row: City) => {
  handleDelete(row.id.toString());
};

// 删除操作
const handleDelete = (ids: string) => {
  ElMessageBox.confirm("确认删除所选城市数据?", "警告", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      try {
        const res: any = await getCityBlackDel({
          id: ids,
        });
        if (res.code === 1) {
          ElMessage.success("删除成功");
          getList();
        } else {
          ElMessage.success("删除失败:", res.msg);
        }
      } catch (error) {
        console.error(error);
      }
    })
    .catch(() => {
      ElMessage.error("取消删除");
    });
};

// 处理表单提交
const handleSubmit = async () => {
  if (!formRef.value) return;

  await formRef.value.validate(async (valid) => {
    if (valid) {
      const cityName = cityOptions.value.find(
        (item) => item.id === form.cityId
      )?.cityname;
      try {
        const res: any = await getCityBlackAdd({
          province_id: form.provinceId,
          city: cityName,
        });
        if (res.code === 1) {
          ElMessage.success("添加成功");
          dialogVisible.value = false;
          getList();
        } else {
          ElMessage.error("添加失败:", res.msg);
        }
      } catch (error) {
        console.error(error);
      }
    }
  });
};

// 处理表格选择变化
const handleSelectionChange = (selection: City[]) => {
  multipleSelection.value = selection;
};

// 处理分页变化
const handleSizeChange = (val: number) => {
  queryParams.limit = val;
  getList();
};

const handleCurrentChange = (val: number) => {
  queryParams.page = val;
  getList();
};

// 初始化
onMounted(() => {
  getList();
});
</script>

<template>
  <div class="urban-shielding-container">
    <!-- 操作按钮区域 -->
    <div class="action-bar">
      <el-button
        type="primary"
        @click="handleAdd">
        添加城市
      </el-button>
      <el-button
        type="danger"
        @click="handleDeleteSelected">
        删除选中
      </el-button>
    </div>

    <!-- 搜索区域 -->
    <div class="search-bar">
      <el-form :inline="true">
        <el-form-item label="城市名称">
          <el-input
            v-model="queryParams.keyword"
            placeholder="请输入城市名称" />
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            @click="handleSearch">
            搜索
          </el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 表格区域 -->
    <div class="table-container">
      <el-table
        v-loading="loading"
        :data="tableData"
        @selection-change="handleSelectionChange"
        border>
        <el-table-column
          type="selection"
          width="55"
          align="center" />
        <el-table-column
          label="ID"
          prop="id"
          width="80"
          align="center" />
        <el-table-column
          label="省份"
          prop="province"
          align="center" />
        <el-table-column
          label="城市"
          prop="city"
          align="center" />
        <el-table-column
          label="添加时间"
          prop="created_at"
          align="center"
          width="180" />
        <el-table-column
          label="操作"
          align="center"
          width="120">
          <template #default="{ row }">
            <el-button
              link
              type="danger"
              size="small"
              @click="handleDeleteItem(row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页区域 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="queryParams.page"
        v-model:page-size="queryParams.limit"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange" />
    </div>

    <!-- 添加/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
      destroy-on-close>
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="80px"
        :inline="true">
        <el-form-item
          label="省份"
          prop="provinceId">
          <el-select
            v-model="form.provinceId"
            placeholder="请选择省份"
            filterable
            clearable
            @change="handleProvinceChange">
            <el-option
              v-for="item in provinceOptions"
              :key="item.id"
              :label="item.cityname"
              :value="item.id" />
          </el-select>
        </el-form-item>

        <el-form-item
          label="城市"
          prop="cityId">
          <el-select
            v-model="form.cityId"
            placeholder="请选择城市"
            filterable
            clearable
            :disabled="!form.provinceId">
            <el-option
              v-for="item in cityOptions"
              :key="item.id"
              :label="item.cityname"
              :value="item.id" />
          </el-select>
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button
            type="primary"
            @click="handleSubmit"
            >保存</el-button
          >
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped lang="scss">
.urban-shielding-container {
  background-color: #fff;
  border-radius: 8px;
  padding: 20px;

  .action-bar {
    margin-bottom: 20px;
  }

  .search-bar {
    margin-bottom: 20px;
  }

  .table-container {
    margin-bottom: 20px;
  }

  .pagination-container {
    display: flex;
    justify-content: flex-end;
  }
}
</style>
